package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;

import data.ArpTemplate;

import arp.ArpTable;
import arp.ArpTableModel;

@SuppressWarnings("serial")
public class ArpPanel extends JPanel implements ActionListener {
	private ArpTableModel model;
	private ArpTable table;
	private Vector<ArpTemplate> templates;
	private ArpTemplate currentTemplate;
	private JLabel lblTemplate, lblSteps, lblLength;
	private JComboBox cmbTemplate, cmbSteps, cmbLength;
	private JFileChooser fileChooser;
	private FileInputStream fis;
	private FileOutputStream fos;
	private Color fgColor, bgColor;
	private Font font;
	
	public ArpPanel(Color fgColor, Color bgColor, Font font, ArpTemplate template) {
		super();
		this.fgColor = fgColor;
		this.bgColor = bgColor;
		this.font = font;
		this.setLayout(new BorderLayout());
		this.setBackground(bgColor);
		this.setBorder(BorderFactory.createLineBorder(fgColor));
		
		setupControlPanel();
		setupTemplates();		
		
		currentTemplate = template;
		
		model = new ArpTableModel(currentTemplate);
		table = new ArpTable(model, fgColor, bgColor, font);
		this.add(table, BorderLayout.CENTER);
		updateComponents();
	}
	
	private void setupTemplates() {
		templates = new Vector<ArpTemplate>();
		// Read templates from template-folder
		String templatedirpath = System.getProperty("user.dir") + System.getProperty("file.separator") + "templates";
		File templatedir = new File(templatedirpath);
		File[] templatefiles = templatedir.listFiles();
		for (File f: templatefiles) {
			System.out.println(f.getName());
			try {
				fis = new FileInputStream(f);
				ArpTemplate template = new ArpTemplate();
				template.deserialize(fis);
				templates.add(template);
				String name = f.getName();
				cmbTemplate.addItem(name.substring(0, name.indexOf(".")));
				currentTemplate = template;
			} 
			catch (FileNotFoundException fne) {
				fne.printStackTrace();
			}
		}		
	}
	
	private void setupControlPanel() {
		JPanel controlPanel = new JPanel();
		controlPanel.setBackground(bgColor);
		
		lblTemplate = new JLabel("TEMPLATE: ");
		lblTemplate.setForeground(fgColor);
		lblTemplate.setFont(font);
		controlPanel.add(lblTemplate);
		
		String[] templateOps = {"NEW", "OPEN", "SAVE", "----------"};
		cmbTemplate = new JComboBox(templateOps);
		cmbTemplate.setBorder(BorderFactory.createLineBorder(fgColor));
		cmbTemplate.setBackground(bgColor);
		cmbTemplate.setForeground(fgColor);
		cmbTemplate.setFont(font);
		cmbTemplate.addActionListener(this);
		controlPanel.add(cmbTemplate);
		
		lblSteps = new JLabel("STEPS: ");
		lblSteps.setForeground(fgColor);
		lblSteps.setFont(font);
		controlPanel.add(lblSteps);
		
		String[] steps = new String[16];
		for (int i = 1; i < 17; i++) steps[i - 1] = "" + i;
		cmbSteps = new JComboBox(steps);
		cmbSteps.setBorder(BorderFactory.createLineBorder(fgColor));
		cmbSteps.setBackground(bgColor);
		cmbSteps.setForeground(fgColor);
		cmbSteps.setFont(font);
		cmbSteps.addActionListener(this);
		controlPanel.add(cmbSteps);
		
		lblLength = new JLabel("LENGTH: ");
		lblLength.setForeground(fgColor);
		lblLength.setFont(font);
		controlPanel.add(lblLength);
		
		String[] length = {"1/4", "1/8", "1/16", "1/32"};
		cmbLength = new JComboBox(length);
		cmbLength.setBorder(BorderFactory.createLineBorder(fgColor));
		cmbLength.setBackground(bgColor);
		cmbLength.setForeground(fgColor);
		cmbLength.setFont(font);
		cmbLength.addActionListener(this);
		controlPanel.add(cmbLength);
		
		this.add(controlPanel, BorderLayout.NORTH);
		
		fileChooser = new JFileChooser();
	}

	@Override
	public void actionPerformed(ActionEvent ae) {
		if (ae.getSource() == cmbSteps) {
			currentTemplate.setSteps(Integer.parseInt((String) cmbSteps.getSelectedItem()));
			model.updateTable();
		}
		else if (ae.getSource() == cmbLength) {
			currentTemplate.setLength((String) cmbLength.getSelectedItem());
		}
		else if (ae.getSource() == cmbTemplate) {
			if (((String) cmbTemplate.getSelectedItem()).equals("New")) {
				currentTemplate = new ArpTemplate(1, "1/16");
				updateComponents();
			}
			else if (((String) cmbTemplate.getSelectedItem()).equals("Open")) {
				int val = fileChooser.showOpenDialog(this);
				if (val == JFileChooser.APPROVE_OPTION) {
					System.out.println("Open...");
					try {
						File file = fileChooser.getSelectedFile();
						fis = new FileInputStream(file);
						
						ArpTemplate template = new ArpTemplate();
						template.deserialize(fis);
						templates.add(template);
												
						String name = file.getName().substring(0, file.getName().indexOf("."));
						
						// Check if item already exists
						for (int i = 0; i < cmbTemplate.getItemCount() - 4; i++) {
							if (cmbTemplate.getItemAt(i + 4).equals(name)) {
								name += "2";
								break;
							}
						}
						cmbTemplate.addItem(name);
						cmbTemplate.setSelectedIndex(cmbTemplate.getItemCount() - 1);
						System.out.println("combox items: " + cmbTemplate.getItemCount());
						System.out.println("template count: " + templates.size());
						
						currentTemplate = template;
						updateComponents();
						
						System.out.println("" + currentTemplate.getSteps() + ", " + currentTemplate.getLength());
					}
					catch (FileNotFoundException fne) {
						fne.printStackTrace();
					}
				}
			}
			else if (((String) cmbTemplate.getSelectedItem()).equals("Save")) {
				int val = fileChooser.showSaveDialog(this);
				if (val == JFileChooser.APPROVE_OPTION) {
					try {
						// TODO use templates Vector
						
						File file = fileChooser.getSelectedFile();
						fos = new FileOutputStream(file);
						currentTemplate.serialize(fos);
						if (!templates.contains(currentTemplate)) {
							String fname = file.getName();
							String name = fname.substring(0, fname.indexOf("."));
							templates.add(currentTemplate);
							cmbTemplate.addItem(name);
							cmbTemplate.setSelectedItem(name);
						}
					}
					catch (FileNotFoundException fne) {
						fne.printStackTrace();
					}
				}
			}
			else {
				// set currenTemplate & update ui components
				currentTemplate = templates.get(cmbTemplate.getSelectedIndex() - 4);
				System.out.println("index combobox: " + (cmbTemplate.getSelectedIndex() - 4));
				System.out.println("index templates: " + templates.indexOf(currentTemplate));
				updateComponents();
			}
		}
	}
	
	private void updateComponents() {
		cmbSteps.setSelectedIndex(currentTemplate.getSteps() - 1);
		cmbLength.setSelectedItem(currentTemplate.getLength());
		model.setTemplate(currentTemplate);
		model.updateTable();
	}
}
